package com.caiheng.api.controller.product;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.caiheng.api.constant.ResponseCode;
import com.caiheng.api.controller.platform.BaseController;
import com.caiheng.api.entity.estate.Estate;
import com.caiheng.api.entity.estate.EstateRoom;
import com.caiheng.api.entity.mer.Mer;
import com.caiheng.api.entity.platform.AdBanner;
import com.caiheng.api.entity.product.*;
import com.caiheng.api.entity.wxuser.User;
import com.caiheng.api.service.estate.EstateRoomService;
import com.caiheng.api.service.estate.EstateService;
import com.caiheng.api.service.mer.MerService;
import com.caiheng.api.service.platfom.AdBannerService;
import com.caiheng.api.service.product.*;
import com.caiheng.api.service.wxuser.UserService;
import com.caiheng.api.util.GsonResultBean;
import com.caiheng.api.util.MathUtil;
import com.caiheng.api.util.Tools;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *@Author: ZhouWei
 *@Description:  用户技能相关接口
 *@Date 2018-05-10
 */
@Component
@RestController
@RequestMapping("/product/type")//url:模块/资源/{}/细分
public class ProductTypeController extends BaseController {

    @Resource
    private ProductTypeService productTypeService;
    @Resource
    private ProductService productService;
    @Resource
    private ProductOrderService productOrderService;
    @Resource
    private EstateRoomService estateRoomService;
    @Resource
    private UserService userService;
    @Resource
    private ProductAttrValueService productAttrValueService;
    @Resource
    private MerService merService;
    @Resource
    private AdBannerService adBannerService;

    @Value("${web.imgPrefixOss}")
    private String imgPrefix;//微信支付的回调地址

    /**
     * 获取所有分类
     * @param
     * @throws Exception
     */
    @PostMapping(value="/list")
    public JSONObject indexPage(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int parent_id = jsonRequest.containsKey("parent_id") ? jsonRequest.getInt("parent_id") : 0;
            int pageIndex = jsonRequest.containsKey("pageIndex")&& StrUtil.isNotEmpty(jsonRequest.get("pageIndex").toString())  ? jsonRequest.getInt("pageIndex") : 1;
            int pageSize = jsonRequest.containsKey("pageSize")&& StrUtil.isNotEmpty(jsonRequest.get("pageSize").toString())  ? jsonRequest.getInt("pageSize") : 10;
            String platform = jsonRequest.containsKey("platform") ? jsonRequest.getStr("platform") : "wxmini";

            double longitude = jsonRequest.containsKey("longitude") ? jsonRequest.getDouble("longitude") : 0;
            double latitude = jsonRequest.containsKey("latitude") ? jsonRequest.getDouble("latitude") : 0;


            Map<String,Object> map = new HashMap<>();
            QueryWrapper<AdBanner> qwBanner = new QueryWrapper<>();
            qwBanner.eq("state",0);
            qwBanner.eq("ad_type",4);
            qwBanner.orderByAsc("sort");
            List<AdBanner> banners = adBannerService.list(qwBanner);
            if(CollUtil.isNotEmpty(banners)){
                banners.forEach(banner->{
                    if(StrUtil.isNotEmpty(banner.getImgUrl())){
                        banner.setImgUrl(imgPrefix + banner.getImgUrl());
                    }
                });
            }
            map.put("banners",banners);

            //1.先获取父节点
            QueryWrapper<ProductType> qw = new QueryWrapper<>();
            qw.eq("state",0);
            qw.eq("is_platform",0);
            if(platform.equals("wxmini")){
                qw.eq("is_show",1);
            }
            qw.eq("parent_id",parent_id);
            qw.orderByAsc("sort");
            List<ProductType> list = productTypeService.list(qw);
            if(CollUtil.isNotEmpty(list)){
                for (ProductType type : list){
                    type.setImgUrl( imgPrefix + type.getImgUrl());
                }
            }
            if(list.size() > 0){
                map.put("typeId",list.get(0).getId());
                List<Product> products = productService.queryProductList("",list.get(0).getId(),0,1,0,platform,pageIndex,pageSize);
                map.put("products",products);
            }
            map.put("types",list);
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",list.size(), map),false,false);
        }catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"系统异常",e.getMessage()),true,true);
            logger.error(e.toString(), e);
        }
        return result;
    }

    /**
     * 获取当前商家的所有分类
     * @param
     * @throws Exception
     */
    @PostMapping(value="/product/list")
    public JSONObject productListByType(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int mer_id = jsonRequest.containsKey("mer_id") ? jsonRequest.getInt("mer_id") : 0;
            int cateId = jsonRequest.containsKey("cateId") ? jsonRequest.getInt("cateId") : 0;

            int pageIndex = jsonRequest.containsKey("pageIndex")&& StrUtil.isNotEmpty(jsonRequest.get("pageIndex").toString())  ? jsonRequest.getInt("pageIndex") : 1;
            int pageSize = 200;// jsonRequest.containsKey("pageSize") ? jsonRequest.getInt("pageSize") : 100;
            int isSearch = jsonRequest.containsKey("isSearch") ? jsonRequest.getInt("isSearch") : 0;

            String keyword = jsonRequest.containsKey("keyword") ? jsonRequest.getStr("keyword") : null;
            String platform = jsonRequest.containsKey("platform") ? jsonRequest.getStr("platform") : "wxmini";

            Map<String,Object> map = new HashMap<>();

            QueryWrapper<ProductOrder> qwOrder = new QueryWrapper<>();
            qwOrder.eq("status",0);
            qwOrder.eq("user_id",user_id);
            qwOrder.eq("mer_id",mer_id);
            long orderCount = productOrderService.count(qwOrder);
            map.put("orderCount", orderCount);

            //只搜索 商品
            //String productName,Integer isHot, int cateChildId, String platform,int pageIndex, int pageSize
            List<Product> products = productService.queryProductList(keyword,0,cateId,platform,pageIndex,pageSize);
            map.put("products",products);
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",products.size(), map),false,false);

        }catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"系统异常",e.getMessage()),true,true);
            logger.error(e.toString(), e);
        }
        return result;
    }

    /**
     * 获取当前商家的所有分类
     * @param
     * @throws Exception
     */
    @PostMapping(value="/platform/product/list")
    public JSONObject platformProductListByType(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int cateId = jsonRequest.containsKey("type_id") ? jsonRequest.getInt("type_id") : 0;

            int pageIndex = jsonRequest.containsKey("pageIndex")&& StrUtil.isNotEmpty(jsonRequest.get("pageIndex").toString())  ? jsonRequest.getInt("pageIndex") : 1;
            int pageSize = jsonRequest.containsKey("pageSize") ? jsonRequest.getInt("pageSize") : 10;

            String keyword = jsonRequest.containsKey("keyword") ? jsonRequest.getStr("keyword") : null;
            String platform = jsonRequest.containsKey("platform") ? jsonRequest.getStr("platform") : "wxmini";

            Map<String,Object> map = new HashMap<>();

            //只搜索 商品
            //String productName,Integer isHot, int cateChildId, String platform,int pageIndex, int pageSize
            List<Product> products = productService.queryProductListPlatform(keyword,0,cateId,platform,pageIndex,pageSize);
            map.put("products",products);
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",products.size(), map),false,false);

        }catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"系统异常",e.getMessage()),true,true);
            logger.error(e.toString(), e);
        }
        return result;
    }

    /**
     * 获取当前商家的所有分类
     * @param
     * @throws Exception
     */
    @PostMapping(value="/estate/list")
    public JSONObject typeListByEstateRoom(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
//            int mer_id = jsonRequest.containsKey("mer_id") ? jsonRequest.getInt("mer_id") : 0;
            int cateId = jsonRequest.containsKey("cateId") ? jsonRequest.getInt("cateId") : 0;
            int estateId = jsonRequest.containsKey("estateId") && StrUtil.isNotEmpty(jsonRequest.getStr("estateId")) ? jsonRequest.getInt("estateId") : 0;
            int pageIndex = jsonRequest.containsKey("pageIndex")&& StrUtil.isNotEmpty(jsonRequest.get("pageIndex").toString())  ? jsonRequest.getInt("pageIndex") : 1;
            int pageSize = jsonRequest.containsKey("pageSize") ? jsonRequest.getInt("pageSize") : 10;
            String keyword = jsonRequest.containsKey("keyword") ? jsonRequest.getStr("keyword") : null;


            User user = userService.findById(user_id);
//            if(user == null){
//                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该用户不存在"),true,true);
//            }

            if(estateId == 0 && user != null){
                List<EstateRoom> estateRoomList = estateRoomService.getRoomListByUserId(user_id,"");
                if(CollUtil.isNotEmpty(estateRoomList)){
//                    estateId = estateRoomList.get(0).getEstateId();
                    estateId = user.getEstateId();
                }
            }
            if(estateId == 0){
                estateId = 1;
            }

            List<Product> products = new ArrayList<>();
            Map<String,Object> map = new HashMap<>();
            if(estateId > 0){
                //1.先获取父节点
                QueryWrapper<ProductType> qw = new QueryWrapper<>();
                qw.eq("state",0);
                qw.eq("is_show",1);
                qw.eq("estate_id",estateId);
                qw.orderByAsc("sort");
                List<ProductType> typeList = productTypeService.list(qw);
                if(CollUtil.isNotEmpty(typeList)){
                    for (ProductType type : typeList){
                        if(StrUtil.isNotEmpty(type.getImgUrl())){
                            type.setImgUrl(imgPrefix + type.getImgUrl());
                        }
                    }

                    if(cateId == 0){
                        cateId = typeList.get(0).getId();
                    }

                    QueryWrapper<Mer> qwMer = new QueryWrapper<>();
                    qwMer.eq("estate_id", estateId);
                    qwMer.eq("shop_type", 2);
                    qwMer.last("limit 1");
                    Mer mer = merService.getOne(qwMer);
                    if(mer != null){
                        //String productName,int merId, int estateId, int productTypeId, int pageIndex, int pageSize
                        products = productService.queryEstateServiceList(keyword,mer.getId(),estateId, cateId, pageIndex,pageSize);
                        map.put("products",products);
                    }
                }
                map.put("types",typeList);
            }

            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",products.size(), map),false,false);

        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"系统异常",e.getMessage()),true,true);
            logger.error(e.toString(), e);
        }
        return result;
    }



    /**
     * 根据小区id获取积分商城的商品分类
     * @param
     * @throws Exception
     */
    @PostMapping(value="/estate/point/list")
    public JSONObject getEstatePointType(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int cateId = jsonRequest.containsKey("cateId") ? jsonRequest.getInt("cateId") : 0;
            int estateId = jsonRequest.containsKey("estateId") && StrUtil.isNotEmpty(jsonRequest.getStr("estateId")) ? jsonRequest.getInt("estateId") : 0;
            int pageIndex = jsonRequest.containsKey("pageIndex")&& StrUtil.isNotEmpty(jsonRequest.get("pageIndex").toString())  ? jsonRequest.getInt("pageIndex") : 1;
            int pageSize = jsonRequest.containsKey("pageSize") ? jsonRequest.getInt("pageSize") : 10;
            String keyword = jsonRequest.containsKey("keyword") ? jsonRequest.getStr("keyword") : null;


            User user = userService.findById(user_id);

            if(estateId == 0){
                List<EstateRoom> estateRoomList = estateRoomService.getRoomListByUserId(user_id,"");
                if(CollUtil.isNotEmpty(estateRoomList)){
                    estateId = user.getEstateId();
                }
            }
            if(estateId == 0){
                estateId = 1;
            }

            List<Product> products = new ArrayList<>();
            Map<String,Object> map = new HashMap<>();
            //1.先获取父节点
            QueryWrapper<ProductType> qw = new QueryWrapper<>();
            qw.eq("state",0);
            qw.eq("is_platform",2);
            qw.eq("is_show",1);
//                qw.eq("estate_id",estateId);
            qw.orderByAsc("sort");
            List<ProductType> typeList = productTypeService.list(qw);
            if(CollUtil.isNotEmpty(typeList)){
                for (ProductType type : typeList){
                    if(StrUtil.isNotEmpty(type.getImgUrl())){
                        type.setImgUrl(imgPrefix + type.getImgUrl());
                    }
                }

                if(cateId == 0){
                    cateId = typeList.get(0).getId();
                }

                if(estateId > 0){
                    products = productService.queryPointProductList(keyword, estateId, cateId, pageIndex,pageSize);
                    map.put("products",products);
                }
            }
            map.put("types",typeList);


            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",products.size(), map),false,false);

        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"系统异常",e.getMessage()),true,true);
            logger.error(e.toString(), e);
        }
        return result;
    }


    /**
     * 获取当前商家的分类下所有商品
     * @param
     * @throws Exception
     */
    @PostMapping(value="/point/product/list")
    public JSONObject pointProductList(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int type_id = jsonRequest.containsKey("type_id") ? jsonRequest.getInt("type_id") : 0;
            int estateId = jsonRequest.containsKey("estateId") && StrUtil.isNotEmpty(jsonRequest.getStr("estateId")) ? jsonRequest.getInt("estateId") : 0;

            int pageIndex = jsonRequest.containsKey("pageIndex")&& StrUtil.isNotEmpty(jsonRequest.get("pageIndex").toString())  ? jsonRequest.getInt("pageIndex") : 1;
            int pageSize = jsonRequest.containsKey("pageSize") ? jsonRequest.getInt("pageSize") : 100;

            String keyword = jsonRequest.containsKey("keyword") ? jsonRequest.getStr("keyword") : null;

            ProductType productType = productTypeService.findById(type_id);
            if(productType == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该类型不存在"),true,true);
            }

            Map<String,Object> map = new HashMap<>();
            //只搜索 商品
            //String productName,Integer isHot, int cateChildId, String platform,int pageIndex, int pageSize
            List<Product> products = productService.queryPointProductList(keyword, estateId, type_id, pageIndex,pageSize);
            map.put("products", products);
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功", products.size(), map),false,false);

        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"系统异常",e.getMessage()),true,true);
            logger.error(e.toString(), e);
        }
        return result;
    }



    /**
     * 获取当前商家的分类下所有商品
     * @param
     * @throws Exception
     */
    @PostMapping(value="/estate/product/list")
    public JSONObject productListEstate(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int type_id = jsonRequest.containsKey("type_id") ? jsonRequest.getInt("type_id") : 0;

            int pageIndex = jsonRequest.containsKey("pageIndex")&& StrUtil.isNotEmpty(jsonRequest.get("pageIndex").toString())  ? jsonRequest.getInt("pageIndex") : 1;
            int pageSize = jsonRequest.containsKey("pageSize") ? jsonRequest.getInt("pageSize") : 100;

            String keyword = jsonRequest.containsKey("keyword") ? jsonRequest.getStr("keyword") : null;

            ProductType productType = productTypeService.findById(type_id);
            if(productType == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该类型不存在"),true,true);
            }

            Map<String,Object> map = new HashMap<>();
            //只搜索 商品
            //String productName,Integer isHot, int cateChildId, String platform,int pageIndex, int pageSize
            List<Product> products = productService.queryEstateServiceList(keyword, productType.getMerId(),productType.getEstateId(),
                                            type_id, pageIndex,pageSize);
            map.put("products", products);
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功", products.size(), map),false,false);

        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"系统异常",e.getMessage()),true,true);
            logger.error(e.toString(), e);
        }
        return result;
    }




    /** 获取所有分类
     * @param
     * @throws Exception
     */
    @PostMapping(value="/childList")
    public JSONObject childlist(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int parent_id = jsonRequest.containsKey("parent_id") ? jsonRequest.getInt("parent_id") : 0;
            Map<String,Object> map = new HashMap<>();
            //1.先获取父节点
            List<String> names = new ArrayList<>();
            List<ProductType> types = productTypeService.selectListByColumn("parent_id",parent_id);
            map.put("types",types);
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",types.size(), map),false,false);
        }catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"系统异常",e.getMessage()),true,true);
            logger.error(e.toString(), e);
        }
        return result;
    }
}
